package com.yicong.ants.ui.scenic;

import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Build;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.util.Pair;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.blankj.utilcode.util.SizeUtils;
import com.cchao.simplelib.core.CollectionHelper;
import com.cchao.simplelib.core.RxHelper;
import com.cchao.simplelib.core.UiHelper;
import com.cchao.simplelib.ui.activity.BaseStatefulActivity;
import com.google.android.material.tabs.TabLayout;
import com.yicong.ants.Constants;
import com.yicong.ants.R;
import com.yicong.ants.bean.scenic.CityItemBean;
import com.yicong.ants.databinding.ScenicTabActivityBinding;
import com.yicong.ants.manager.UserManager;
import com.yicong.ants.manager.config.ZzConfigs;
import com.yicong.ants.manager.http.RetrofitHelper;
import com.yicong.ants.utils.KeyBoardUtils;
import com.yicong.ants.utils.StatusBarUtil;
import com.yicong.ants.utils.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

public class ScenicTabActivity extends BaseStatefulActivity<ScenicTabActivityBinding> implements View.OnClickListener {
    private final List<Pair<String, ScenicListFragment>> mFragments = new ArrayList<>();

    private EditText editSearch;
    private List<CityItemBean> mCityList;
    private String search_name;
    private String mCityId = "0";
    private int page = 0;

    @Override
    protected int getLayout() {
        return R.layout.scenic_tab_activity;
    }

    @Override
    protected void initEventAndData() {
        mDataBind.setClick(this);
        getWindow().setStatusBarColor(Color.TRANSPARENT);
        StatusBarUtil.setTextDarkAndFullScreen(getWindow());
        initSearchView();
        //initAdapter();
        initPage();
        onLoadData();
    }

    private void initSearchView() {
        editSearch = mDataBind.editSearch;
        editSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (StringUtils.isNull(editSearch.getText().toString())) {
                    search_name = null;
                }
            }
        });
        editSearch.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                initSearch();
            }
            return false;
        });
    }

    private void initPage() {
        mFragments.add(Pair.create("预约景区", new ScenicListFragment()
                .setScenicType(Constants.Scenic_Type.SetAdvanceScenic)));
        mFragments.add(Pair.create("免预约景区", new ScenicListFragment()
                .setScenicType(Constants.Scenic_Type.PartnerScenic)));

        mDataBind.viewPage.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int i) {
                return mFragments.get(i).second;
            }

            @Override
            public int getCount() {
                return mFragments.size();
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return mFragments.get(position).first;
            }
        });
        mDataBind.viewPage.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                page = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        mDataBind.tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                TextView tv = (TextView) tab.getCustomView();
                if (tv != null)
                    tv.setTypeface(Typeface.DEFAULT_BOLD);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                TextView tv = (TextView) tab.getCustomView();
                if (tv != null)
                    tv.setTypeface(Typeface.DEFAULT);
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                TextView tv = (TextView) tab.getCustomView();
                if (tv != null)
                    tv.setTypeface(Typeface.DEFAULT);
            }
        });
        mDataBind.tabLayout.setupWithViewPager(mDataBind.viewPage);
        //获取TabLayout设置的字体颜色,包含tabTextColor及tabSelectedTextColor
        ColorStateList colorStateList = mDataBind.tabLayout.getTabTextColors();
        //对每个Tab 设置customView，设置为TextView，用于设置字体大小等
        for (int i = 0; i < mDataBind.tabLayout.getTabCount(); i++) {
            TabLayout.Tab tab = mDataBind.tabLayout.getTabAt(i);
            assert tab != null;
            String tabStr = Objects.requireNonNull(tab.getText()).toString();
            if (tab.getCustomView() == null || !(tab.getCustomView() instanceof TextView)) {
                TextView tv = new TextView(mDataBind.tabLayout.getContext());
                tv.setTextColor(colorStateList);
                tv.setText(tabStr);
                tv.setTextSize(16);
                tv.setTypeface(tab.isSelected() ? Typeface.DEFAULT_BOLD : Typeface.DEFAULT);
                tab.setCustomView(tv);
                tab.view.setLongClickable(false);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    tab.view.setTooltipText(null);
                }
            }
        }

        mDataBind.viewPage.setOffscreenPageLimit(mFragments.size());
    }

    @Override
    protected void onLoadData() {
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.draw_txt:
                KeyBoardUtils.closeKeybord(editSearch, editSearch.getContext());
                if (CollectionHelper.isNotEmpty(mCityList)) {
                    showProvinceSelect();
                    return;
                }
                showProgress();
                addSubscribe(RetrofitHelper.getApis().city_list(Collections.emptyMap())
                        .compose(RxHelper.toMain())
                        .subscribe(respBean -> {
                            hideProgress();
                            if (respBean.isCodeFail()) {
                                showToast(respBean.getMsg());
                                return;
                            }
                            mCityList = CollectionHelper.isEmpty(respBean.getData()) ? new ArrayList<>() : respBean.getData();
                            CityItemBean bean = new CityItemBean();
                            bean.setCity_id("0");
                            bean.setName("全国");
                            mCityList.add(0, bean);
                            showProvinceSelect();
                        }, RxHelper.getHideProgressConsumer(this)));
                break;
            case R.id.info:
                ZzConfigs.toWebActivityByUrlNotLogin(mContext, "ant_rule_coin");
                break;
            case R.id.my_bill:
                if (!UserManager.isNotAuthElseTurn(mContext)) {
                    ZzConfigs.toWebActivityByUrl(mContext, "scenic_order");
                }
                break;
        }
    }

    private void initSearch() {
        if (StringUtils.isNull(editSearch.getText().toString())) {
            showToast("请输入关键字");
            return;
        }
        KeyBoardUtils.closeKeybord(editSearch, editSearch.getContext());
        search_name = editSearch.getText().toString();
        mFragments.get(page).second.search(mCityId, search_name);
    }

    private void showProvinceSelect() {
        OptionsPickerView<CityItemBean> pvOptions = new OptionsPickerBuilder(mContext, (options1, options2, options3, v) -> {
            mDataBind.drawTxt.setText(mCityList.get(options1).getName());
            mCityId = mCityList.get(options1).getCity_id();
            onLoadData();
        }).setTitleText("省份选择")
                .setDividerColor(UiHelper.getColor(R.color.text_666))
                .setTextColorCenter(UiHelper.getColor(R.color.text_222)) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();

        pvOptions.setPicker(mCityList);//三级选择器
        pvOptions.show();
    }
}
